package ru.yermak.spring;

import org.springframework.beans.factory.config.Scope;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.stereotype.Component;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.awt.event.ActionEvent;

/**
 * User: harrier
 * Date: Nov 16, 2008
 */
@Component
public class EventScope implements Scope {
    private Log log = LogFactory.getLog(EventScope.class);

    private ScopedActionEvent event;

    public Object get(String name, ObjectFactory objectFactory) {
        String threadName = Thread.currentThread().getName();
        log.debug("threadName = " + threadName);

        log.debug("Looking in EventScope fo name = " + name);
        if (event.getAttribute(name) != null) {
            log.debug("Returning cached instance for name = " + name);
            return event.getAttribute(name);
        } else {
            Object obj = objectFactory.getObject();
            log.debug("Creating new instance for name = " + name);
            event.setAttribute(name, obj);
            return obj;
        }
    }

    public Object remove(String name) {
        log.debug("Removing instance by name = " + name);
        return event.removeAttribute(name);
    }

    public void registerDestructionCallback(String name, Runnable runnable) {
    }

    public String getConversationId() {
        return String.valueOf(event.getWhen());
    }

    public void start(ActionEvent e) {
        System.out.println("EventScope.start");
        event = new ScopedActionEvent(e);
    }

    public void end() {
        System.out.println("EventScope.end");
        event = null;
    }
}
